<template>
  <div>
    <div class="container">

      <el-page-header @back="goBack" content="" style="padding-bottom: 40px">
        <template v-if="optType === 'update'">
          <span slot="content">修改酒品</span>
        </template>
        <template v-else>
          <span slot="content">新增酒品</span>
        </template>
      </el-page-header>


      <el-form ref="ruleForm"
               :model="ruleForm"
               :rules="rules"
               label-width="180px">
        <div>
          <el-form-item label="酒品名称:"
                        prop="name">
            <el-input v-model="ruleForm.name"
                      placeholder="请填写酒品名称"
                      maxlength="14"/>
          </el-form-item>
          <el-form-item label="酒品分类:"
                        prop="categoryId">
            <el-select v-model="ruleForm.categoryId"
                       placeholder="请选择酒品分类">
              <el-option v-for="(item, index) in winepackageList"
                         :key="index"
                         :label="item.name"
                         :value="item.id"/>
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="酒品价格:"
                        prop="price">
            <el-input v-model="ruleForm.price"
                      placeholder="请设置酒品价格"/>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="酒品规格:"
                        required>
            <el-form-item>
              <div class="specificationBox">
              <span v-if="specifications.length == 0"
                    class="addBut"
                    @click="addSpecification">
                + 添加规格</span>
                <div v-if ="specifications.length != 0"
                     class="specification">
                  <div class="title">
                    <span>规格名（3个字内）</span>
                  </div>
                  <div class="cont">
                    <div v-for="(item, index) in specifications"
                         :key="index"
                         class="items">
                      <div class="itTit">

                        <AddSpecification :select-specifications-data="leftSpecifications"
                                     :index="index"
                                     :name="item.name"
                                     @select="selectHandle" />
                      </div>

                      <div class="labItems"
                           style="display: flex">
                      <span v-for="(it, ind) in item.value"
                            :key="ind">{{ it }}
                        <i @click="delSpecificationLabel(index, ind)">X</i></span>
                        <div class="inputBox"
                             :style="{flex:1}" />
                      </div>
                      <span class="delSpecification delBut non"
                            @click="delSpecification(item.name)">删除</span>
                    </div>
                  </div>
                  <div v-if="
                       !!this.leftSpecifications.length &&
                         this.specifications.length < this.specificationsData.length
                     "
                       class="addBut"
                       @click="addSpecification()">
                    添加规格
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="酒品图片:"
                        required
                        prop="image">

            <img-upload :prop-image-url="imageUrl"
                        @imageChange="imageChange">
              图片大小不超过2M<br>仅能上传 PNG JPEG JPG类型图片<br>建议上传200*200或300*300尺寸的图片
            </img-upload>
          </el-form-item>
        </div>
        <div class="address">
          <el-form-item label="酒品描述:">
            <el-input v-model="ruleForm.description"
                      type="textarea"
                      :rows="3"
                      maxlength="200"
                      placeholder="酒品描述，最长200字"/>
          </el-form-item>
        </div>

        <div>
          <div class="subBox">
            <el-button type="primary" @click="submitForm('ruleForm',false)">保存</el-button>
            <el-button
                v-if="this.optType ==='add'"
                type="primary"
                @click="submitForm('ruleForm',true)">保存并继续添加酒品
            </el-button>
          </div>
        </div>
      </el-form>

    </div>
  </div>
</template>

<script>
import request from "@/utils/request";
import AddSpecification from "@/views/wine/components/addSpecification.vue";
import ImgUpload from "@/components/ImgUpload.vue";

export default {
  components: {
    AddSpecification,
    ImgUpload,
  },
  data() {
    return {
      value: '',
      winepackageList: [],
      seachKey: '',
      specificationsData:[],//原始规格数据
      specifications: [],//待上传规格的数据
      wineList:[],
      imageUrl: '',
      specificationTable: [],
      leftSpecifications:  [], //下拉框剩余可选择的规格数据
      index : 0,
      title: '',
      optType: 'add',

      ruleForm: {
        name: '',
        categoryId: '',
        price: '',
        code: '',
        image: '',
        description: '',
        specifications: [],
        status: true,
      },
      rules: {
        name: [
          {required: true, message: '酒品名称', trigger: 'blur'},
          {validator: this.validator, trigger: 'blur'}
        ],
        categoryId: {required: true, message: '请选择酒品分类', trigger: 'change'},
        image: {required: true, message: '酒品图片不能为空'},
        price: [
          {required: true, message: '请输入价格', trigger: 'blur'},
          {validator: this.pricce, trigger: 'blur'}
        ],
      },

    }
  },
  watch: {
    specifications: {
      handler() {
        this.getLeftSpecifications();
      },
    },
  },
  created() {
    //看是否携带参数过来，携带的话就使用更新
    // 查询酒品分类，用于填充查询页面的下拉框
    request.get(`/admin/category/list/${1}`).then(res => {
      if (res.code == 1) {
        this.winepackageList = res.data
      }else {
        this.$message.error(res.msg)
      }
    })
    // 规格临时数据
    this.getSpecificationListHand()
    this.optType = this.$route.query.id ? 'update' : 'add'
    if (this.optType === 'update') {
      request.get(`/admin/wine/${this.$route.query.id}`).then(res => {
        if (res.code == 1) {
          this.ruleForm = res.data
          this.ruleForm.status = res.data.status
          this.ruleForm.price = res.data.price
          this.imageUrl = res.data.image
          this.specifications =
              res.data.specifications &&
              res.data.specifications.map(obj => ({
                ...obj,
                value: JSON.parse(obj.value)
              }))
          this.getLeftSpecifications()
        } else {
          this.$message.error(res.msg)
        }
      })
    }
  },
  methods: {
//过滤已选择的规格下拉框无法再次选择
    getLeftSpecifications() {
      let arr = []
      this.specificationsData.map(item => {
        if (
            this.specifications.findIndex(item1 => item.name == item1.name) === -1
        ) {
          arr.push(item)
        }
      })
      this.leftSpecifications = arr
    },
// 获取临时规格列表列表
    getSpecificationListHand() {
  this.specificationsData = [
    { name: '包装', value: ['带盒', '裸瓶'] },
    { name: '温度', value: ['低温', '常温'] }
  ]
},
    // 规格
    addSpecification() {
        this.specifications.push({ name: '', value: [] })
    },

    delSpecification(name) {
      let ind = this.specifications.findIndex(item => item.name === name);
      if (ind !== -1) {
        this.specifications.splice(ind, 1);
      }
    },

    delSpecificationLabel(index, ind) {
        this.specifications[index].value.splice(ind, 1);
    },
    selectHandle(val, key, ind) {
      const arrDate = [...this.specifications];
      const dataIndex = this.specificationsData.findIndex(item => item.name === val);

      if (dataIndex !== -1) {
        arrDate[key] = JSON.parse(JSON.stringify(this.specificationsData[dataIndex]));
        this.specifications = arrDate;
      }
    },

    goBack() {
      const currentRoute = this.$route.path;
      if (currentRoute !== '/wine') {
        this.$router.push('/wine');
      }
    },
    pricce(rule, value, callback) {
      const reg = /^([1-9]\d{0,5}|0)(\.\d{1,2})?$/
      if (!reg.test(value) || Number(value) <= 0) {
        callback(
            new Error(
                '请输入大于零且最多保留两位小数的金额'
            )
        )
      } else {
        callback()
      }
    },
    validator(rule, value, callback) {
      const reg = /^[\u4e00-\u9fa5_a-zA-Z0-9().]{1,12}$/
      if (!value) {
        callback(new Error('请输入酒品名称'))
      } else if (!reg.test(value)) {
        callback(new Error('名称输入不符，请输入1-12个字符'))
      } else {
        callback()
      }
    },
    submitForm(formName, isContinue) {
      //$refs是引用的ref属性，通过ref可以获取到组件实例，通过实例可以调用组件的方法
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.ruleForm.image) return this.$message.error('酒品图片不能为空')
          this.ruleForm.status = this.optType === 'add' ? 0 : this.ruleForm.status ? 1 : 0
          // this.ruleForm.categoryId = this.ruleForm.categoryId
          this.ruleForm.specifications=this.specifications.map(item => ({
            ...item,
            value: JSON.stringify(item.value)
          }))
          if (this.optType === 'add') {      //新增操作
            request.post('/admin/wine', this.ruleForm).then(res => {
              if (res.code === 1) {
                this.$message.success('酒品添加成功！')
                if (isContinue) {
                  this.ruleForm = {
                    specifications: [],
                    specificationTable: [],
                    ruleForm: {
                      name: '',
                      categoryId: '',
                      price: '',
                      code: '',
                      image: '',
                      description: '',
                      specifications: [],
                      status: true,
                      id: '',
                    },
                    imageUrl: ''
                  }
                } else {
                  this.$router.push('/wine')
                }
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {     //修改操作
            request.put('/admin/wine', this.ruleForm).then(res => {
              if (res.code === 1) {
                this.$message.success('修改成功')
                this.$router.push('/wine')
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    imageChange(value) {
      this.ruleForm.image = value
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-input {
  width: 200px;
}

.container {
  position: relative;
  z-index: 1;
  background: #fff;
  padding: 30px;
  border-radius: 4px;

  .subBox {
    padding-top: 30px;
    text-align: center;
    border-top: solid 1px $gray-5;
  }

}





.specificationBox {
  width: 777px;

  .addBut {
    background: #409EFF;
    display: inline-block;
    padding: 0px 20px;
    border-radius: 3px;
    line-height: 40px;
    cursor: pointer;
    border-radius: 4px;
    color: white;
    font-weight: 500;
  }

  .specification {
    border: solid 1px #dfe2e8;
    border-radius: 3px;
    padding: 15px;
    background: #fafafb;

    .title {
      color: #606168;
      .des-box {
        padding-left: 44px;
      }
    }

    .cont {
      .items {
        display: flex;
        margin: 10px 0;

        .itTit {
          width: 150px;
          margin-right: 15px;

          input {
            width: 100%;
          }
        }

        .labItems {
          flex: 1;
          display: flex;
          flex-wrap: wrap;
          border-radius: 3px;
          min-height: 30px;
          border: solid 1px #d8dde3;
          background: #fff;
          padding: 0 5px;

          span {
            display: inline-block;
            color: #ffc200;
            margin: 5px;
            line-height: 26px;
            padding: 0 10px;
            background: #fffbf0;
            border: 1px solid #fbe396;
            border-radius: 4px;
            font-size: 12px;

            i {
              cursor: pointer;
              font-style: normal;
            }
          }

          .inputBox {
            display: inline-block;
            width: 100%;
            height: 30px;
            line-height: 30px;
            overflow: hidden;
          }
        }

        .delSpecification {
          display: inline-block;
          padding: 0 10px;
          color: #f19c59;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
